package com.freewater.cargotracker.infrastructure.allocation;

import com.freewater.cargotracker.domain.model.cargo.Cargo;
import com.freewater.cargotracker.domain.model.cargo.EnterpriseSegment;
import com.freewater.cargotracker.domain.model.cargo.RouteSpecification;
import com.freewater.cargotracker.domain.service.AllocationCheckerService;

import java.util.HashSet;
import java.util.Set;

public class AllocationCheckerServiceImpl implements AllocationCheckerService {

    private final SalesManagementInterface salesManagementInterface;

    public AllocationCheckerServiceImpl(SalesManagementInterface salesManagementInterface) {
        this.salesManagementInterface = salesManagementInterface;
    }

    @Override
    public EnterpriseSegment derivedEnterpriseSegment(Cargo cargo) {
        RouteSpecification routeSpecification = cargo.getRouteSpecification();
        String originLocationName = routeSpecification.getOrigin().getName();
        String destLocationName = routeSpecification.getDestination().getName();
        Set<String> categoryNames = new HashSet<>();
        // 简单实用出发地和收货地的名称作为segments，实际情况肯定不是这样的。
        // 也可能调用SalesManagementInterface接口来生成segments。
        categoryNames.add(originLocationName);
        categoryNames.add(destLocationName);
        return new EnterpriseSegment(categoryNames);
    }

    @Override
    public boolean mayAccept(Cargo cargo, int quantityBooked) {
        EnterpriseSegment enterpriseSegment = this.derivedEnterpriseSegment(cargo);
        String categoryList = String.join(",", enterpriseSegment.getCategoryNames());
        int allocation = this.salesManagementInterface.allocation(categoryList);
        return quantityBooked + cargo.getSize() <= allocation;
    }
}
